package com.dongdongshop.service.impl;


import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.pojo.TbGoodsDesc;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.service.ItemPageService;
import com.dongdongshop.service.TbGoodsDescService;
import com.dongdongshop.service.TbGoodsService;
import com.dongdongshop.service.TbItemService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ItemPageServiceImpl implements ItemPageService {

    @Reference
    private TbGoodsService tbGoodsService;

    @Reference
    private TbGoodsDescService tbGoodsDescService;

    @Reference
    private TbItemService tbItemService;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Override
    public void createPage(Long goodsId) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        FileWriter writer =null;
        try {
            // 4. 加载一个模板创建模板对象
            Template template = configuration.getTemplate("item.ftl");
            // 5. 创建模板使用的数据集   可以是pojo  map  常用map
            Map map = new HashMap();
            // 6. 创建一个Writer对象 指定生成文件的路径
            writer = new FileWriter("D:\\X_code\\freemarker\\"+goodsId+".html");
            // 数据填充
            // 根据goodsId 查询商品信息
            TbGoods tbGoods = tbGoodsService.selectByGoodsId(goodsId);
            map.put("tbGoods",tbGoods);
            // 根据goodsId 查询商品信息
            TbGoodsDesc tbGoodsDesc = tbGoodsDescService.selectByGoodsId(goodsId);
            map.put("tbGoodsDesc",tbGoodsDesc);
            // 根据Id 查询 item 数据
            List<TbItem> itemList = tbItemService.selectItemByGoodsId(goodsId);
            map.put("itemList",itemList);


            // 7. 调用模板对象的 process 方法  生成页面
            template.process(map,writer);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (writer!=null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
